package com.endpoint.search.listener;

import com.endpoint.common.utils.ResultBean;
import com.endpoint.search.feign.BookFeignService;
import com.endpoint.search.service.SearchService;
import com.endpoint.search.to.BookEsModel;
import com.endpoint.search.to.BookTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Project: endpoint
 * @Name: BookVisitListener
 * @Author: Jack_Li
 * @Date: 2024/7/8 19:50
 */
@Component
@Slf4j
public class BookVisitAddListener {

    @Autowired
    private BookFeignService bookFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SearchService searchService;


    //更新数据库 流量削峰，每本小说累积10个点击更新一次
    @RabbitListener(queues = {"UPDATE-ES-QUEUE"})
    public void updateEs(Long bookId, Channel channel, Message message) {

        log.debug("收到更新搜索引擎消息：" + bookId);
        if (redisTemplate.opsForValue().get("esIsUpdateVisit:" + bookId) == null) {
            redisTemplate.opsForValue().set("esIsUpdateVisit:" + bookId, "1", 60 * 60);
            try {
                Thread.sleep(1000 * 5);
                ResultBean<BookTo> book = bookFeignService.getById(bookId);
                BookEsModel res = new BookEsModel();
                BeanUtils.copyProperties(book.getData(), res);

                searchService.importToEs(res);
            }catch (Exception e){
                redisTemplate.delete("esIsUpdateVisit:" + bookId);
                log.error("更新搜索引擎失败"+bookId);
            }
        }
    }
}